import pymysql

class DBtool:

    @classmethod
    def __get_mysql(cls):
        conn=pymysql.connect(host='localhost',port=3306,user='root',password='root',charset='utf8',database='test01')
        return conn

    @classmethod  # 查询一条
    def select_one(cls, sql,args):
        cursor = None
        conn = None
        res = None
        try:
            conn = cls.__get_mysql()  # 1.建立连接
            cursor = conn.cursor(pymysql.cursors.DictCursor)  # 2.获取游标
            cursor.execute(sql,args)
            res = cursor.fetchone()
        except Exception as e:
            print('查询一条时遇到错误' + str(e))
        finally:
            cursor.close()
            conn.close()
            return res

    @classmethod  # 查询多条
    def select_many(cls, sql, num):
        cursor = None
        conn = None
        res = None
        try:
            conn = cls.__get_mysql()  # 1.建立连接
            cursor = conn.cursor(pymysql.cursors.DictCursor)  # 2.获取游标
            cursor.execute(sql)
            res = cursor.fetchmany(num)
        except Exception as e:
            print('查询一条时遇到错误' + str(e))
        finally:
            cursor.close()
            conn.close()
            return res

    @classmethod  # 查询一条
    def select_all(cls, sql):
        cursor = None
        conn = None
        res = None
        try:
            conn = cls.__get_mysql()  # 1.建立连接
            cursor = conn.cursor(pymysql.cursors.DictCursor)  # 2.获取游标
            cursor.execute(sql)
            res = cursor.fetchall()
        except Exception as e:
            print('查询一条时遇到错误' + str(e))
        finally:
            cursor.close()
            conn.close()
            return res

    # 增删改
    @classmethod
    def iud_db(cls, sql,args):
        cursor = None
        conn = None
        try:
            conn = cls.__get_mysql()
            cursor = conn.cursor()
            cursor.execute(sql,args)
            conn.commit()
        except Exception as e:
            print('进行增删改操作出错' + str(e))
            conn.rollback()
        finally:
            cursor.close()
            conn.close()

if __name__ == '__main__':
    # res=DBtool.select_one('select * from student where stu_name="%s"',"曹操")
    # print(res)
    SQL='select * from student where stu_name="%s"'
    DBtool.iud_db(SQL,"曹操")
















